/**********************************************************************
 *@Project： clouddemo
 *@File: AresErrorHandle
 *@Date: 2017/4/16
 *@Copyright (C) 2013-2017 http://www.posun.cn. All Rights Reserved.
 ***********************************************************************
 *注意： 本内容仅限于深圳市普盛实业有限公司内部使用，禁止外泄
 **********************************************************************
 */
package com.posun.edu.common.controller;

import com.alibaba.fastjson.JSON;
import com.posun.cloud.tracing.enums.LogType;
import com.posun.framework.dto.Result;
import com.posun.framework.enums.ResultCode;
import com.posun.framework.log.AresLog;
import com.posun.framework.log.LogBuilder;
import com.posun.framework.util.StringUtil;
import org.apache.shiro.session.UnknownSessionException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * <p>
 * 全局web异常处理<br>
 *
 * @author YL
 * @version 1.0
 * @createTime 2017/4/16 18:38
 * @ChangeLog
 */
@ControllerAdvice
public class AresErrorHandle {

    @ExceptionHandler(UnknownSessionException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ModelAndView processUnknownSessionException(HttpServletRequest request, UnknownSessionException e) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/login?sessionOut=1");
        return mv;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView processException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        AresLog.error(new LogBuilder(AresErrorHandle.class, LogType.EXCEPTION, e.getMessage(), e));
        e.printStackTrace();
        ModelAndView mv = new ModelAndView();
        if (isAjaxRequest(request)) {
            try {
                Result result = new Result(ResultCode.UNKNOWN_ERROR, e.getMessage());
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(result));
                writer.flush();
                writer.close();
                return null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            mv.addObject("error", e.getMessage());
            mv.setViewName("error/5xx");
        }
        return mv;
    }

    private boolean isAjaxRequest(HttpServletRequest request) {
        String xRequestedWith = request.getHeader("X-Requested-With");
        String restRequest = request.getHeader("content-type");
        if (StringUtil.isNotEmpty(xRequestedWith) ||
                (StringUtil.isNotEmpty(restRequest) && restRequest.contains("json"))) {
            return true;
        }
        return false;
    }
}
